package com.gill.touka.service;

import com.gill.touka.domain.dto.UserLoginDTO;
import com.gill.touka.domain.entity.BonusEventLog;
import com.gill.touka.mapper.BonusEventLogMapper;
import com.gill.touka.mapper.UserMapper;
import com.gill.touka.domain.entity.User;
import com.gill.touka.mq.AddBonusMsg;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Slf4j
@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private BonusEventLogMapper bonusEventLogMapper;

    public User findById(Integer id){
        return userMapper.selectByPrimaryKey(id);
    }

    @Transactional(rollbackFor = Exception.class)
    public void addBonus(AddBonusMsg msg){
        // 1、为用户加积分
        Integer id = msg.getId();
        User user = userMapper.selectByPrimaryKey(id);
        if(user == null){
            log.warn("用户不存在，创建id为666、积分为0的用户，方便在日志表观察");
            user = User.builder().id(666).bonus(0).build();
        }else{
            user.setBonus(user.getBonus() + msg.getBonus());
            userMapper.updateByPrimaryKey(user);
        }
        // 2、记录日志
        bonusEventLogMapper.insert(BonusEventLog.builder()
                .userId(user.getId())
                .value(user.getBonus())
                .event("添加积分")
                .description("添加积分")
                .createTime(new Date())
                .build());
    }

    /**
     * 若当前用户已经注册，直接返回；若当前用户未注册，直接为其注册并返回。（这里为了简单实现，直接将注册逻辑变为简单的插入逻辑）
     * @param loginDTO 用户登录信息
     * @param openId 用户在微信小程序服务端的唯一id
     * @return 用户信息
     */
    public User login(UserLoginDTO loginDTO, String openId){
        User user = this.userMapper.selectOne(
                User.builder()
                        .wxId(openId)
                        .build()
        );
        // 当前用户未注册，直接注册并返回
        if (user == null) {
            User userToSave = User.builder()
                    .wxId(openId)
                    .bonus(300)
                    .wxNickname(loginDTO.getWxNickname())
                    .avatarUrl(loginDTO.getAvatarUrl())
                    .roles("user")
                    .createTime(new Date())
                    .updateTime(new Date())
                    .build();
            this.userMapper.insertSelective(
                    userToSave
            );
            return userToSave;
        }
        // 当前用户已注册，直接返回
        return user;
    }
}
